package com.millstein.config;

import com.millstein.properties.RabbitMQProperties;
import org.springframework.amqp.core.*;
import org.springframework.amqp.support.converter.Jackson2JsonMessageConverter;
import org.springframework.amqp.support.converter.MessageConverter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * @description:
 * @author: tsing
 * @create: 2021-09-19 20:42
 */
@Configuration
@EnableConfigurationProperties(RabbitMQProperties.class)
public class RabbitMQConfig {

    @Autowired
    private RabbitMQProperties properties;

    /**
     * 消息转换器，注意是support包里的
     * @return
     */
    @Bean
    public MessageConverter messageConverter() {
        return new Jackson2JsonMessageConverter();
    }

    /**
     * 创建交换机
     * @return
     */
    @Bean
    public Exchange exchange() {
        return ExchangeBuilder.topicExchange(properties.getCouponEventExchange()).durable(true).build();
    }

    /**
     * 创建延时队列
     * @return
     */
    @Bean
    public Queue couponReleaseDelayQueue() {
        return QueueBuilder
                .durable(properties.getCouponReleaseDelayQueue())
                .deadLetterExchange(properties.getCouponEventExchange())
                .deadLetterRoutingKey(properties.getCouponReleaseRoutingKey())
                .ttl(Integer.parseInt(properties.getTtl()))
                .build();
    }

    /**
     * 创建死信队列
     * @return
     */
    @Bean
    public Queue couponReleaseQueue() {
        return QueueBuilder
                .durable(properties.getCouponReleaseQueue())
                .build();
    }

    /**
     * 绑定延时队列
     * @return
     */
    @Bean
    public Binding bindingDelayQueue() {
        return BindingBuilder
                .bind(couponReleaseDelayQueue())
                .to(exchange())
                .with(properties.getCouponReleaseDelayRoutingKey())
                .noargs();
    }

    /**
     * 绑定死信队列
     * @return
     */
    @Bean
    public Binding bindingQueue() {
        return BindingBuilder
                .bind(couponReleaseQueue())
                .to(exchange())
                .with(properties.getCouponReleaseRoutingKey())
                .noargs();
    }
}
